﻿// (c) Copyright Clovis Coli Jr.
// This source is subject to the Microsoft Public License.
// See http://www.microsoft.com/opensource/licenses.mspx#Ms-PL.
// All other rights reserved.

using System.Windows;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Media;

namespace BrasilFramework.Controle.WPF.Comum.Validacao
{
	public class ValidatorManager : FrameworkElement
	{
		public class ManagerList
		{
			public FrameworkElement Element { get; set; }
			public ValidatorBase Validator { get; set; }
		}

        readonly HashSet<ManagerList> _items = new HashSet<ManagerList>();

        public ValidatorManager()
        {
            InvalidBorder = new SolidColorBrush(Colors.Red);
            InvalidBorderThickness = new Thickness(2);
        }

		public void Register(FrameworkElement elementToValidate, ValidatorBase v)
		{
			_items.Add(new ManagerList { Element = elementToValidate, Validator = v });
		}

        public void Unregister(FrameworkElement elementToValidate, ValidatorBase v)
        {
            _items.RemoveWhere(item => item.Element == elementToValidate && item.Validator == v);
        }

		public List<ValidatorBase> ValidateAll()
		{
		    return (from item in _items where !item.Validator.Validate(true) select item.Validator).ToList();
		}

		public static string GetErrorString(IEnumerable<string> list, string delimiter)
		{
			string s = list.Aggregate("", (current, item) => current + (item + delimiter));
		    return s.TrimEnd(delimiter.ToCharArray());
		}

		public static string GetErrorString(IEnumerable<ValidatorBase> list, string delimiter)
		{
			return GetErrorString(
				list.Select(n => n.ErrorMessage).ToList(), delimiter);
		}

        public Brush InvalidBackground
        {
            get;
            set;
        }

        public Brush InvalidBorder
        {
            get;
            set;
        }

        public Thickness InvalidBorderThickness
        {
            get;
            set;
        }

	}

}
